<?php

include_once 'campaigns_protoweb.php';

/**
 * @package Protoweb
 * @subpackage controller
 */
class Campaigns extends Campaigns_protoweb {

  public function __construct() {
    parent::__construct();
  }


  public function create() {

    // Get global instance's objects
    $data['user']   = $this->security();
    $data['client'] = $this->get_client();

    // Assigning messages
    $data['error'] = $this->session->userdata('error');

    // flush message's buffer
    $this->session->set_userdata('error', '');

    // Get client's templates
    $data['templates'] = new Template();
    $data['templates']->where('client_id', $data['client']->id)->get();

    // Get path to templates
    $data['templates_path'] = $this->config->item("clients_url") . $data['client']->slug . '/templates/';
    
    if ($this->input->server('REQUEST_METHOD') === 'POST')
      $data = $this->create_save();

    $this->smarty_parser->view('campaign_create.html', $data);
  } // end of method create()


  private function create_save() {

    // Get global instance's objects
    $data['user']     = $this->security();
    $data['client']   = $this->get_client();
    $data['campaign'] = new Campaign();

    // check if a template was selected
    if ($this->input->post('template') == '') {
      $this->session->set_userdata('error','Please select a template');
      redirect(base_url()."campaigns/create/".$data['campaign']->id."/");
    }

    // Get the selected template
    $template = new Template($this->input->post('template')); 

    $data['campaign']->created  = date('Y-m-d H:i:s');
    $data['campaign']->from     = $this->input->post("from");
    $data['campaign']->name     = $this->input->post("name");
    $data['campaign']->subject  = $this->input->post("subject");
    $data['campaign']->tplbody  = $this->template_parser($template->keyname, $data['client']->slug);
    $data['campaign']->body     = NULL;
    $data['campaign']->filters  = NULL;
    $data['campaign']->sent     = 0;
    $data['campaign']->shipment = 0;

    //saving attributes
    if ( ! $data['campaign']->save(array($data['client'],$template))) {
      $this->session->set_userdata('error',$data['campaign']->error->string);
      redirect(base_url()."campaigns/create/".$data['campaign']->id."/");
    }
    else {
      $campaign_path = $this->config->item('clients_path') . $data['client']->slug . '/campaigns/' . $data['campaign']->id;
      mkdir($campaign_path);
      chmod($campaign_path, 0755);
      redirect(base_url()."campaigns/edit/".$data['campaign']->id."/");
    }
  } // end of method create_save()


  public function settings($id=0) {

    // Get global instance's objects
    $data['user']     = $this->security();
    $data['client']   = $this->get_client();
    $data['campaign'] = new Campaign($id);

    // Security: redirect if haven't ID
    if ($id === 0)
      redirect(base_url()."campaigns/create/");

    if ($this->input->server('REQUEST_METHOD') === 'POST')
      $data = $this->settings_save($id);

    // Assigning messages
    $data['error'] = $this->session->userdata('error');

    // Get client's templates
    $data['templates'] = new Template();
    $data['templates']->where('client_id', $data['client']->id)->get();

    // Get path to templates
    $data['templates_path'] = $this->config->item("clients_url") . $data['client']->slug . '/templates/';

    // flush message's buffer
    $this->session->set_userdata('error', '');
    
    // Activate the corresponding tab option
    $data['active'] = 'campaign';

    $this->smarty_parser->view('campaign_create.html', $data);
  } // end of method edit()


  private function settings_save($id) {
    $data['error'] = "";

    // Get global instance's objects
    $data['user']     = $this->security();
    $data['client']   = $this->get_client();
    $data['campaign'] = new Campaign($id);

    // Assign value to field. If value is empty, we will assign NULL
    $data['campaign']->from = $this->input->post("from");
    if ($data['campaign']->from == "") 
      $data['campaign']->from = NULL;
    
    // Assign value to field. If value is empty, we will assign NULL
    $data['campaign']->name = $this->input->post("name");
    if ($data['campaign']->name == "") 
      $data['campaign']->name = NULL;
    
    // Assign value to field. If value is empty, we will assign NULL
    $data['campaign']->subject = $this->input->post("subject");
    if ($data['campaign']->subject == "") 
      $data['campaign']->subject = NULL;
    
    //saving attributes
    if( ! $data['campaign']->save())
      $data['error'] .= $data['campaign']->error->string;

    redirect(base_url()."campaigns/edit/".$data['campaign']->id."/");
  } // end of method settings_save()


  public function edit($id=0) {

    // Get global instance's objects
    $data['user']   = $this->security();
    $data['client'] = $this->get_client();

    // Security: redirect if haven't ID
    if ($id === 0)
      redirect(base_url()."campaigns/create/");

    // Get data from Campaign Object
    $data['campaign'] = new Campaign($id);

    if ($this->input->server('REQUEST_METHOD') === 'POST')
      $data = $this->edit_save($data['campaign']->id);

    $data['campaign']->css = $this->config->item("clients_url") . 
                             $data['client']->slug . '/templates/' . 
                             $data['campaign']->template->keyname . '/' . 
                             $data['campaign']->template->keyname . '.css';

    // Activate the corresponding tab option
    $data['active'] = 'campaign';
    
    $this->smarty_parser->view('campaign_edit.html', $data);
  } // end of method edit($id=0)


  public function save($id) {
    $data["message"] = "success";

    // Get global instance's objects
    $data['user']     = $this->security();
    $data['client']   = $this->get_client();
    $data['campaign'] = new Campaign($id);

    // Assign value to field. If value is empty, we will assign NULL
    $data['campaign']->tplbody = $this->input->post("tplbody");
    if ($data['campaign']->tplbody == "")
      $data['campaign']->tplbody = NULL;

    // Assign value to field. If value is empty, we will assign NULL
    $data['campaign']->body = trim($this->input->post("body"));
    if ($data['campaign']->body == "")
      $data['campaign']->body = NULL;

    //saving attributes
    if( ! $data["campaign"]->save())
      $data["message"] = $data["campaign"]->error->string;
    



    // agregamos el css inline
    include_once("emogrifier.php");
    $css = file_get_contents($this->config->item('clients_url') . "{$data['client']->slug}/templates/{$data['campaign']->template->keyname}/{$data['campaign']->template->keyname}.css");
    $css2inline = new Emogrifier($data["campaign"]->body, $css);
    
    // guardamos el body en la base
    $data["campaign"]->body = $css2inline->emogrify();

    // Generates an HTML content's campaign
    $this->load->helper('file');
    write_file("clients/".$data['client']->slug . "/campaigns/{$id}/index.html", $data["campaign"]->body);




    die($data["message"]);
  } // end of method edit_save($id)


  public function saveimage($id) {

    // Get global instance's objects
    $data['user']     = $this->security();
    $data['client']   = $this->get_client();
    $data['campaign'] = new Campaign($id);

    // Assign value to field
    $url      = $this->input->post("url");
    $width    = ($this->input->post("width") > 0) ? $this->input->post("width") : NULL;
    $height   = ($this->input->post("height") > 0) ? $this->input->post("height") : NULL;
    $filename = $this->input->post("name");
    $filename = str_replace("#", "", $filename) . ".jpg";

    // chequeamos si la URL existe
    $gestor = @fopen($url, "r");
    if ( ! $gestor) 
      die($this->config->item('clients_url') . "picture-blank.jpg");

    include_once('phpthumb.class.php');
    try {
      $filename = $data['client']->slug . "/campaigns/{$id}/{$filename}";

      $phpThumb = new phpThumb();
      $phpThumb->setSourceFilename($url);
      $phpThumb->setParameter('w', $width);
      $phpThumb->setParameter('h', $height);
      $phpThumb->setParameter('f', 'jpeg');

      $phpThumb->GenerateThumbnail();
      $phpThumb->RenderToFile($this->config->item('clients_path').$filename);

      $filename = $this->config->item('clients_url') . $filename;
    }

    //catch exception
    catch(Exception $error) {
      $filename = $url; // $error->getMessage()
    }
      
    die($filename);
  } // end of method saveimage($id)

  // Este método NO DEBERÍA ENVIAR sino solamente preparar 
  // la tabla campaigns para que el daemon se encargue del envío
  public function send($id) {
    // Get global instance's objects
    $data['user']     = $this->security();
    $data['client']   = $this->get_client();
    $data['campaign'] = new Campaign($id);
  
    // agregamos el css inline
    include_once("emogrifier.php");
    $css = file_get_contents($this->config->item('clients_url') . "{$data['client']->slug}/templates/{$data['campaign']->template->keyname}/{$data['campaign']->template->keyname}.css");
    $css2inline = new Emogrifier($data['campaign']->body, $css);
    
    // guardamos el body en la base
    $data['campaign']->body = $css2inline->emogrify();
    $data['campaign']->save();

    // Generates an HTML content's campaign
    write_file($this->config->item('clients_path') . $data['client']->slug . "/campaigns/{$id}/index.html", $data['campaign']->body);

    // Generate rows in sends table
    $data['campaign']->generate_sends();

    // set sent date for campaing
    $data['campaign']->sent = date('Y-m-d H:i:s');
    $data['campaign']->save();

    redirect(base_url()."users/dashboard/");
  } // end of method send($id)

  private function template_parser($tpl, $client_slug) {
    include_once("parser.php");

    return $html->find('body',0)->innertext;
  } 

  public function stats($id) {
    // Get global instance's objects
    $user     = $this->security();
    $client   = $this->get_client();
    $campaign = new Campaign($id);

    $response = array(
      'delivered'   => $campaign->sends_delivered() ,
      'bounced'     => $campaign->sends_bounced() ,
      'count'       => $campaign->sends_count(),
      'read'        => $campaign->sends_read(),
      'undelivered' => $campaign->sends_undelivered()
    );

    die(json_encode($response));
  } // stats

  public function delete($id) {

    // Get global instance's objects
    $user     = $this->security();
    $client   = $this->get_client();
    $campaign = new Campaign($id);

    // delete
    if ($campaign->delete())
      $this->session->set_userdata('success', 'La campaña se borró correctamente');
    else
      $this->session->set_userdata('error', $campaign->error->string);

    redirect(base_url()."users/dashboard/");
  } // delete($id)
   
  public function history() {
    // Get global instance's objects
    $data['user']   = $this->security();
    $data['client'] = $this->get_client();

    $data['campaigns'] = new Campaign();
    $data['campaigns']->where_related_client('id',$data['client']->id)->order_by('created','desc')->get();

    $this->smarty_parser->view('campaign_history.html', $data);
  }

} // class Campaigns

/* End of file campaigns.php */
/* Location: ./system/application/controllers/campaigns.php */